package com.ruoyi.common.utils;

import org.docx4j.Docx4J;
import org.docx4j.convert.out.pdf.PdfConversion;
import org.docx4j.convert.out.pdf.viaXSLFO.PdfSettings;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;


import javax.servlet.http.HttpServletResponse;;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.concurrent.ExecutorService;

// 文件下载工具类
public class FileDownloadUtil {
    
    /**
     * 生成Word并直接响应下载
     * @param entity 数据实体
     * @param templatePath 模板路径
     * @param fileName 下载文件名
     * @param response HttpServletResponse
     */
    public static void downloadWord(Object entity, 
                                   String templatePath,
                                   String fileName,
                                   HttpServletResponse response) throws Exception {
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        
        // 直接生成到响应流
        try (OutputStream out = response.getOutputStream()) {
            WordTemplateUtils.fillTemplate(entity, templatePath, out);
        }
    }

    /**
     * 生成PDF并直接响应下载
     * @param entity 数据实体
     * @param templatePath 模板路径
     * @param fileName 下载文件名
     * @param response HttpServletResponse
     */
    public static void downloadPDF(Object entity,
                                   String templatePath,
                                   String fileName,
                                   HttpServletResponse response) throws Exception {
        // 设置响应头
        response.setContentType("application/pdf; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        // 兼容不同浏览器的文件名编码
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; " +
                "filename*=utf-8''" + encodedFileName);

        // 生成内存中的Word文档
        ByteArrayOutputStream docxOut = new ByteArrayOutputStream();
        WordTemplateUtils.fillTemplate(entity, templatePath, docxOut);

        // 转换为PDF并输出
        try (OutputStream pdfOut = response.getOutputStream()) {
            WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(
                    new ByteArrayInputStream(docxOut.toByteArray()));
            Docx4J.toPDF(wordMLPackage, pdfOut);
            // 确保数据全部写入并刷新缓冲区
            pdfOut.flush();
        }catch (Exception e){
            throw new Exception("PDF转换失败", e);
        }
    }
}
